/**
 * Copyright © 2012, 2013 dr. ir. Jeroen M. Valk
 * 
 * This file is part of ComPosiX.
 * 
 * ComPosiX is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * ComPosiX is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * ComPosiX. If not, see <http://www.gnu.org/licenses/>.
 */

function assert(condition) {
	if (!condition) {
		throw new Error("assertion error");
	}
}

function is_tuple(x) {
	return typeof x == 'object' && typeof x.length == "number";
}

function is_string(x) {
	return typeof x == "string";
}

function exists(condition, base, members) {
	var result = false;
	for ( var i in base) {
		if (condition(base, i)) {
			if (members == null) {
				return true;
			} else {
				result = true;
				members[i] = base[i];
			}
		}
	}
	return result;
}

function forall(condition, base, members) {
	return !exists(not(condition), base, members);
}

function not(condition) {
	return function(x, i) {
		return !condition(x, i);
	};
}

function inverse(family) {
	var result = {};
	for ( var i in family) {
		var value = family[i];
		assert(typeof (value) == 'number' || typeof (value) == 'string');
		if (!result[value]) {
			result[value] = [];
		}
		result[value].push(i);
	}
	return result;
}

function card(family) {
	return inverse(family).length;
}

function aggregate(family, operator) {
	var current = null;
	for ( var i in y) {
		if (current == null) {
			current = [ i, family[i] ];
		} else {
			operator(current, i, family[i]);
		}
	}
	return current;
}

function is_pair(x) {
	return x instanceof Array && x.length == 2;
}
